package com.sloan.community.listener;

import io.r2dbc.proxy.core.*;
import io.r2dbc.proxy.listener.ProxyExecutionListener;
import io.r2dbc.proxy.support.MethodExecutionInfoFormatter;
import io.r2dbc.proxy.support.QueryExecutionInfoFormatter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.SortedSet;

/**
 * @Author: yaosj
 * @CreateTime: 2024-12-19
 * 参考官方文档：https://r2dbc.io/r2dbc-proxy/docs/current/docs/html/#components_formatters
 */
@Slf4j
public class CommunityProxyExecutionListener implements ProxyExecutionListener {

    static QueryExecutionInfoFormatter queryExecutionInfoFormatter;
    static MethodExecutionInfoFormatter methodExecutionInfoFormatter;

    static {
        queryExecutionInfoFormatter = new QueryExecutionInfoFormatter().newLine()
                .delimiter(" => ")
                .showThread()
                .showTime()
                .showQuery()
                .showBindings();
        methodExecutionInfoFormatter = MethodExecutionInfoFormatter.withDefault();
    }

    @Override
    public void beforeMethod(MethodExecutionInfo executionInfo) {
//        String str = methodExecutionInfoFormatter.format(executionInfo);
//        log.info("community beforeMethod：{}",str);
    }

    @Override
    public void afterMethod(MethodExecutionInfo executionInfo) {
//        String str = methodExecutionInfoFormatter.format(executionInfo);
//        log.info("community afterMethod：{}",str);
    }

    @Override
    public void beforeQuery(QueryExecutionInfo execInfo) {
        String str = queryExecutionInfoFormatter.format(execInfo);
        log.info("community beforeQuery：{}", str);
//        List<QueryInfo> queries = execInfo.getQueries();
//        for (QueryInfo query : queries) {
//            String sql = query.getQuery();
//            List<Bindings> bindingsList = query.getBindingsList();
//            for (Bindings bindings : bindingsList) {
//                SortedSet<Binding> indexBindings = bindings.getIndexBindings();
//                for (Binding indexBinding : indexBindings) {
//                    Object key = indexBinding.getKey();
//                    Object value = indexBinding.getBoundValue().getValue();
//                }
//                SortedSet<Binding> namedBindings = bindings.getNamedBindings();
//                for (Binding namedBinding : namedBindings) {
//                    Object key = namedBinding.getKey();
//                    Object value = namedBinding.getBoundValue().getValue();
//                }
//            }
//        }
    }

    @Override
    public void afterQuery(QueryExecutionInfo execInfo) {
//        String str = queryExecutionInfoFormatter.format(execInfo);
//        log.info("community afterQuery：{}", str);
    }

    @Override
    public void eachQueryResult(QueryExecutionInfo execInfo) {
//        String str = queryExecutionInfoFormatter.format(execInfo);
//        log.info("community eachQueryResult：{}", str);
    }
}
